<template>
	<div class="business-application-container">
		<!-- 搜索区域 -->
		<el-card class="search-card">
			<el-form :model="searchForm" class="search-form">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-form-item label="申请类型">
							<el-select
								v-model="searchForm.applicationType"
								placeholder="请选择申请类型"
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in applicationTypeOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="申请状态">
							<el-select
								v-model="searchForm.applicationStatus"
								placeholder="请选择申请状态"
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in applicationStatusOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="申请人">
							<el-select
								v-model="searchForm.applicant"
								placeholder="请选择申请人"
								style="width: 100%"
							>
								<el-option
									v-for="item in userOptions"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="申请时间">
							<el-date-picker
								v-model="searchForm.applicationTime"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="YYYY-MM-DD"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="4">
						<div class="form-actions">
							<el-button
								type="primary"
								@click="handleSearch"
								:loading="loading"
							>
								<el-icon class="el-icon--left">
									<Search />
								</el-icon>
								查询
							</el-button>
							<el-button @click="resetSearch">
								<el-icon class="el-icon--left">
									<Refresh />
								</el-icon>
								重置
							</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 操作按钮区域 -->
		<el-card class="action-card">
			<div class="action-buttons">
				<el-button type="primary" @click="handleAdd">
					<el-icon class="el-icon--left">
						<Plus />
					</el-icon>
					新增申请
				</el-button>
				<el-button @click="refreshData">
					<el-icon class="el-icon--left">
						<Refresh />
					</el-icon>
					刷新
				</el-button>
			</div>

			<el-table
				:data="tableData"
				v-loading="loading"
				border
				style="width: 100%; margin-top: 20px"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" align="center" />

				<el-table-column
					prop="applicant"
					label="申请人"
					align="center"
					width="120"
				>
					<template #default="{ row }">
						{{ getName(userOptions, row.applicant, "id", "name") }}
						<!-- <span>{{ getUserName(row.applicant) || row.applicant }}</span> -->
					</template>
				</el-table-column>

				<el-table-column
					prop="applicationType"
					label="申请类型"
					align="center"
					width="120"
				>
					<template #default="{ row }">
						<el-tag
							:type="getApplicationTypeTag(row.applicationType)"
							size="small"
						>
							{{ getApplicationTypeText(row.applicationType) }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column
					prop="applicationTime"
					label="申请时间"
					align="center"
					width="160"
				>
					<template #default="{ row }">
						<span>{{ formatDateTime(row.applicationTime) }}</span>
					</template>
				</el-table-column>

				<el-table-column
					prop="applicationStatus"
					label="申请状态"
					align="center"
					width="120"
				>
					<template #default="{ row }">
						<el-tag
							:type="getApplicationStatusTag(row.applicationStatus)"
							size="small"
						>
							{{ getApplicationStatusText(row.applicationStatus) }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column
					prop="applicationContent"
					label="申请内容"
					align="center"
					min-width="200"
					show-overflow-tooltip
				>
					<template #default="{ row }">
						<span>{{ row.applicationContent || "-" }}</span>
					</template>
				</el-table-column>

				<el-table-column label="操作" align="center" width="280" fixed="right">
					<template #default="{ row }">
						<el-button
							type="primary"
							link
							size="small"
							@click="handleView(row)"
						>
							查看
						</el-button>
						<el-button
							v-if="canEdit(row)"
							type="warning"
							link
							size="small"
							@click="handleEdit(row)"
						>
							编辑
						</el-button>
						<el-button
							v-if="canApprove(row)"
							type="success"
							link
							size="small"
							@click="handleApprove(row)"
						>
							通过
						</el-button>
						<el-button
							v-if="canApprove(row)"
							type="danger"
							link
							size="small"
							@click="handleReject(row)"
						>
							驳回
						</el-button>
						<!-- <el-button
							v-if="canDelete(row)"
							type="danger"
							link
							size="small"
							@click="handleDelete(row)"
						>
							删除
						</el-button> -->
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-container" v-if="tableData.length > 0">
				<el-pagination
					v-model:current-page="pagination.currentPage"
					v-model:page-size="pagination.pageSize"
					:total="pagination.total"
					:page-sizes="[10, 20, 50, 100]"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>

			<div v-if="tableData.length === 0" class="empty-table">
				<el-empty description="暂无数据" :image-size="80" />
			</div>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="800px"
			:before-close="handleCloseDialog"
		>
			<el-form
				ref="formRef"
				:model="formData"
				:rules="formRules"
				label-width="100px"
				class="application-form"
			>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="申请人" prop="applicant">
							<el-select
								v-model="formData.applicant"
								placeholder="请选择申请人"
								style="width: 100%"
							>
								<el-option
									v-for="item in userOptions"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
						<el-form-item label="申请类型" prop="applicationType">
							<el-select
								v-model="formData.applicationType"
								placeholder="请选择申请类型"
								style="width: 100%"
							>
								<el-option
									v-for="item in applicationTypeOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="申请时间" prop="applicationTime">
							<el-date-picker
								v-model="formData.applicationTime"
								type="datetime"
								placeholder="选择申请时间"
								value-format="YYYY-MM-DD HH:mm:ss"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="申请内容" prop="applicationContent">
							<el-input
								v-model="formData.applicationContent"
								type="textarea"
								:rows="4"
								placeholder="请输入申请内容"
								maxlength="1000"
								show-word-limit
							/>
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="附件上传">
							<uploadFile ref="childRef" @success="uploadSuccess" accept="*" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<el-button @click="handleCloseDialog">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="submitting">
					{{ dialogType === "add" ? "提交申请" : "保存修改" }}
				</el-button>
			</template>
		</el-dialog>

		<!-- 查看详情对话框 -->
		<el-dialog
			v-model="viewDialogVisible"
			title="申请详情"
			width="700px"
			:before-close="handleCloseViewDialog"
		>
			<div v-if="currentDetail" class="application-detail">
				<el-descriptions title="基本信息" :column="2" border>
					<el-descriptions-item label="申请ID">{{
						currentDetail.id || "-"
					}}</el-descriptions-item>
					<el-descriptions-item label="申请人">{{
						getUserName(currentDetail.applicant) ||
						currentDetail.applicant ||
						"-"
					}}</el-descriptions-item>
					<el-descriptions-item label="申请类型">
						<el-tag
							:type="getApplicationTypeTag(currentDetail.applicationType)"
							size="small"
						>
							{{ getApplicationTypeText(currentDetail.applicationType) }}
						</el-tag>
					</el-descriptions-item>
					<el-descriptions-item label="申请时间">{{
						formatDateTime(currentDetail.applicationTime) || "-"
					}}</el-descriptions-item>
					<el-descriptions-item label="申请状态">
						<el-tag
							:type="getApplicationStatusTag(currentDetail.applicationStatus)"
							size="small"
						>
							{{ getApplicationStatusText(currentDetail.applicationStatus) }}
						</el-tag>
					</el-descriptions-item>
				</el-descriptions>

				<el-descriptions title="申请内容" :column="1" border class="mt-3">
					<el-descriptions-item label="申请内容">
						<div class="content-text">
							{{ currentDetail.applicationContent || "无" }}
						</div>
					</el-descriptions-item>
				</el-descriptions>

				<el-descriptions
					v-if="currentDetail.fileList"
					title="附件信息"
					:column="1"
					border
					class="mt-3"
				>
					<el-descriptions-item
						label="附件列表"
						:span="2"
						v-if="currentDetail.fileList && currentDetail.fileList.length > 0"
					>
						<div
							v-for="file in currentDetail.fileList"
							:key="file.fileId"
							class="file-item"
						>
							<el-link type="primary" :href="file.filePath" target="_blank">{{
								file.originalFileName
							}}</el-link>
							<span class="file-size"
								>({{ (file.fileSize / 1024).toFixed(2) }} MB)</span
							>
						</div>
					</el-descriptions-item>
				</el-descriptions>
			</div>

			<template #footer>
				<el-button @click="handleCloseViewDialog">关闭</el-button>
				<el-button
					v-if="canApprove(currentDetail)"
					type="success"
					@click="handleApprove(currentDetail)"
				>
					通过申请
				</el-button>
				<el-button
					v-if="canApprove(currentDetail)"
					type="danger"
					@click="handleReject(currentDetail)"
				>
					驳回申请
				</el-button>
			</template>
		</el-dialog>

		<!-- 审批对话框 -->
		<el-dialog
			v-model="approveDialogVisible"
			:title="approveDialogTitle"
			width="500px"
			:before-close="handleCloseApproveDialog"
		>
			<el-form
				ref="approveFormRef"
				:model="approveForm"
				:rules="approveFormRules"
				label-width="80px"
			>
				<el-form-item label="处理动作" prop="operate">
					<el-radio-group v-model="approveForm.operate">
						<el-radio :label="1">通过</el-radio>
						<el-radio :label="2">驳回</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="处理内容" prop="operateContent">
					<el-input
						v-model="approveForm.operateContent"
						type="textarea"
						:rows="4"
						placeholder="请输入处理意见或说明"
						maxlength="500"
						show-word-limit
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button @click="handleCloseApproveDialog">取消</el-button>
				<el-button
					type="primary"
					@click="handleApproveSubmit"
					:loading="approving"
				>
					确认处理
				</el-button>
			</template>
		</el-dialog>

		<!-- 附件查看对话框 -->
		<el-dialog
			v-model="fileDialogVisible"
			title="附件列表"
			width="600px"
			:before-close="handleCloseFileDialog"
		>
			<div v-if="currentFiles.length > 0" class="file-list-dialog">
				<el-table :data="currentFiles" border>
					<el-table-column prop="fileName" label="文件名" min-width="200" />
					<el-table-column prop="fileSize" label="文件大小" width="100">
						<template #default="{ row }">
							{{ formatFileSize(row.fileSize) }}
						</template>
					</el-table-column>
					<el-table-column prop="uploadTime" label="上传时间" width="160">
						<template #default="{ row }">
							{{ formatDateTime(row.uploadTime) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="120">
						<template #default="{ row }">
							<el-button
								type="primary"
								link
								size="small"
								@click="handleDownloadFile(row)"
							>
								下载
							</el-button>
							<el-button
								type="info"
								link
								size="small"
								@click="handlePreviewFile(row)"
							>
								预览
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div v-else class="empty-files">
				<el-empty description="暂无附件" :image-size="60" />
			</div>

			<template #footer>
				<el-button @click="handleCloseFileDialog">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, nextTick, computed } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import dayjs from "dayjs";
	import { getUserList } from "@/api/prod_operate/synthesis/worder";
	import UploadFile from "@/components/UploadFile";
	// 图标引入
	import {
		Search,
		Refresh,
		Plus,
		Download,
		Check,
		Close,
		Delete,
		Document,
		Upload,
	} from "@element-plus/icons-vue";

	// API引入
	import {
		getApplicationTypeList,
		getApplicationStatusList,
		getApplicationActionList,
		getBusinessApplicationList,
		getBusinessApplicationDetail,
		addBusinessApplication,
		updateBusinessApplication,
		deleteBusinessApplication,
		handleApplication,
	} from "@/api/prod_operate/synthesis/business";

	const userOptions = ref([]);
	// 获取用户列表
	const fetchUserList = async () => {
		try {
			const res = await getUserList();
			userOptions.value = res.data || [];
		} catch (error) {
			console.error("获取用户列表失败:", error);
			ElMessage.error("获取用户列表失败");
		}
	};
	const getName = (list, value, keyField, nameField) => {
		const item = list.find((item) => item[keyField] === value);
		return item ? item[nameField] : "-";
	};
	// 响应式数据
	const loading = ref(false);
	const submitting = ref(false);
	const approving = ref(false);

	// 下拉选项
	const applicationTypeOptions = ref([]);
	const applicationStatusOptions = ref([]);
	const applicationActionOptions = ref([]);

	// 搜索表单
	const searchForm = reactive({
		applicationType: "",
		applicationStatus: "",
		applicant: "",
		applicationTime: "",
		applicationContent: "",
		createTime: "",
	});

	// 分页参数
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0,
	});

	// 表格数据
	const tableData = ref([]);
	const selectedRows = ref([]);

	const childRef = ref(null);
	// 对话框控制
	const dialogVisible = ref(false);
	const viewDialogVisible = ref(false);
	const approveDialogVisible = ref(false);
	const fileDialogVisible = ref(false);
	const dialogType = ref("add"); // add/edit

	// 表单引用
	const formRef = ref();
	const approveFormRef = ref();

	const formData = reactive({
		id: "",
		applicant: "", // 保留空默认值，编辑时会覆盖
		applicationType: "",
		applicationTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
		applicationContent: "",
		fileIds: "",
	});

	// 审批表单数据
	const approveForm = reactive({
		applicationId: "",
		operate: 1,
		operateContent: "",
	});

	// 文件列表
	const fileList = ref([]);
	const currentFiles = ref([]);

	// 当前详情
	const currentDetail = ref(null);

	// 表单验证规则
	const formRules = {
		applicationType: [
			{ required: true, message: "请选择申请类型", trigger: "change" },
		],
		applicationTime: [
			{ required: true, message: "请选择申请时间", trigger: "change" },
		],
		applicationContent: [
			{ required: true, message: "请输入申请内容", trigger: "blur" },
			{ min: 10, message: "申请内容至少10个字符", trigger: "blur" },
		],
	};

	// 审批表单验证规则
	const approveFormRules = {
		operate: [{ required: true, message: "请选择处理动作", trigger: "change" }],
		operateContent: [
			{ required: true, message: "请输入处理内容", trigger: "blur" },
			{ min: 5, message: "处理内容至少5个字符", trigger: "blur" },
		],
	};

	// 计算属性
	const dialogTitle = computed(() => {
		return dialogType.value === "add" ? "新增业务申请" : "编辑业务申请";
	});

	const approveDialogTitle = computed(() => {
		return `审批申请 - ${currentDetail.value ? currentDetail.value.id : ""}`;
	});

	// 初始化数据
	onMounted(() => {
		initData();
	});

	// 初始化数据
	const initData = async () => {
		try {
			await Promise.all([
				loadApplicationTypeList(),
				loadApplicationStatusList(),
				loadApplicationActionList(),
				fetchUserList(),
			]);
			await loadApplicationList();
		} catch (error) {
			console.error("初始化数据失败:", error);
			ElMessage.error("初始化数据失败");
		}
	};

	// 修复申请类型回显：确保下拉选项的 dictValue 与表单值类型一致
	const loadApplicationTypeList = async () => {
		try {
			const res = await getApplicationTypeList();
			if (res.code === 200) {
				// 强制将 dictValue 转为字符串（避免数字/字符串类型不匹配导致回显失败）
				applicationTypeOptions.value = (res.data || []).map((item) => ({
					...item,
					dictValue: String(item.dictValue),
				}));
			}
		} catch (error) {
			console.error("加载申请类型列表失败:", error);
			ElMessage.error("加载申请类型列表失败");
		}
	};

	// 修复申请状态回显：同理处理状态选项的类型
	const loadApplicationStatusList = async () => {
		try {
			const res = await getApplicationStatusList();
			if (res.code === 200) {
				applicationStatusOptions.value = (res.data || []).map((item) => ({
					...item,
					dictValue: String(item.dictValue),
				}));
			}
		} catch (error) {
			console.error("加载申请状态列表失败:", error);
			ElMessage.error("加载申请状态列表失败");
		}
	};

	// 加载申请动作列表
	const loadApplicationActionList = async () => {
		try {
			const res = await getApplicationActionList();
			if (res.code === 200) {
				applicationActionOptions.value = res.data || [];
			}
		} catch (error) {
			console.error("加载申请动作列表失败:", error);
			ElMessage.error("加载申请动作列表失败");
		}
	};

	// 加载申请列表
	const loadApplicationList = async () => {
		try {
			loading.value = true;

			const params = {
				applicationType: searchForm.applicationType,
				applicationStatus: searchForm.applicationStatus,
				applicant: searchForm.applicant,
				applicationContent: searchForm.applicationContent,
				pageNum: pagination.currentPage,
				pageSize: pagination.pageSize,
			};

			// 处理时间范围
			if (
				searchForm.applicationTime &&
				searchForm.applicationTime.length === 2
			) {
				params.startApplicationTime = searchForm.applicationTime[0];
				params.endApplicationTime = searchForm.applicationTime[1];
			}

			if (searchForm.createTime && searchForm.createTime.length === 2) {
				params.startCreateTime = searchForm.createTime[0];
				params.endCreateTime = searchForm.createTime[1];
			}

			const res = await getBusinessApplicationList(params);

			if (res.code === 200) {
				tableData.value = res.rows || [];
				pagination.total = res.total || 0;
			} else {
				ElMessage.error(res.msg || "获取申请列表失败");
			}
		} catch (error) {
			console.error("获取申请列表失败:", error);
			ElMessage.error("获取申请列表失败");
		} finally {
			loading.value = false;
		}
	};

	// 处理查询
	const handleSearch = () => {
		pagination.currentPage = 1;
		loadApplicationList();
	};

	// 重置搜索
	const resetSearch = () => {
		Object.assign(searchForm, {
			applicationType: "",
			applicationStatus: "",
			applicant: "",
			applicationTime: "",
			applicationContent: "",
			createTime: "",
		});
		pagination.currentPage = 1;
		handleSearch();
	};

	// 刷新数据
	const refreshData = () => {
		loadApplicationList();
		ElMessage.success("数据已刷新");
	};

	// 处理选择变化
	const handleSelectionChange = (selection) => {
		selectedRows.value = selection;
	};

	// 新增申请
	const handleAdd = () => {
		dialogType.value = "add";
		resetForm();
		dialogVisible.value = true;
	};

	// 查看详情
	const handleView = async (row) => {
		try {
			const res = await getBusinessApplicationDetail(row.id);
			if (res.code === 200 && res.data) {
				currentDetail.value = res.data;
				viewDialogVisible.value = true;
			} else {
				ElMessage.error("获取详情失败");
			}
		} catch (error) {
			console.error("获取详情失败:", error);
			ElMessage.error("获取详情失败");
		}
	};

	// 修复编辑弹窗数据赋值逻辑（确保所有字段正确映射）
	const handleEdit = async (row) => {
		try {
			const res = await getBusinessApplicationDetail(row.id);
			if (res.code === 200 && res.data) {
				dialogType.value = "edit";
				// 完整映射所有字段，包括 applicant
				Object.assign(formData, {
					...res.data,
					// 确保时间格式正确（避免回显时日期组件异常）
					applicationTime: res.data.applicationTime
						? dayjs(res.data.applicationTime).format("YYYY-MM-DD HH:mm:ss")
						: dayjs().format("YYYY-MM-DD HH:mm:ss"),
				});
				dialogVisible.value = true;
			} else {
				ElMessage.error("获取编辑数据失败");
			}
		} catch (error) {
			console.error("获取编辑数据失败:", error);
			ElMessage.error("获取编辑数据失败");
		}
	};

	// 删除申请
	const handleDelete = async (row) => {
		try {
			await ElMessageBox.confirm(`确定要删除申请 "${row.id}" 吗？`, "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			});

			await deleteBusinessApplication(row.id);
			ElMessage.success("删除成功");
			loadApplicationList();
		} catch (error) {
			if (error !== "cancel") {
				console.error("删除失败:", error);
				ElMessage.error("删除失败");
			}
		}
	};

	// 批量删除
	const handleBatchDelete = async () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning("请选择要删除的记录");
			return;
		}

		try {
			await ElMessageBox.confirm(
				`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
				"提示",
				{
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}
			);

			const ids = selectedRows.value.map((item) => item.id).join(",");
			await deleteBusinessApplication(ids);
			ElMessage.success("批量删除成功");
			selectedRows.value = [];
			loadApplicationList();
		} catch (error) {
			if (error !== "cancel") {
				console.error("批量删除失败:", error);
				ElMessage.error("批量删除失败");
			}
		}
	};

	// 审批申请
	const handleApprove = (row) => {
		currentDetail.value = row;
		approveForm.applicationId = row.id;
		approveForm.operate = 1;
		approveForm.operateContent = "";
		approveDialogVisible.value = true;
	};

	// 驳回申请
	const handleReject = (row) => {
		currentDetail.value = row;
		approveForm.applicationId = row.id;
		approveForm.operate = 2;
		approveForm.operateContent = "";
		approveDialogVisible.value = true;
	};

	// 下载文件
	const handleDownloadFile = (file) => {
		ElMessage.info(`下载文件: ${file.fileName}`);
	};

	// 预览文件
	const handlePreviewFile = (file) => {
		ElMessage.info(`预览文件: ${file.fileName}`);
	};

	// 重置表单
	// 修复关闭弹窗时的表单重置逻辑（确保 applicant 也被重置）
	const resetForm = () => {
		Object.assign(formData, {
			id: "",
			applicant: "", // 重置 applicant
			applicationType: "",
			applicationTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
			applicationContent: "",
			fileIds: "",
		});
		fileList.value = [];
		if (formRef.value) {
			formRef.value.clearValidate();
		}
	};

	// 关闭对话框
	const handleCloseDialog = () => {
		dialogVisible.value = false;
		childRef.value?.clearFileList();
		resetForm();
	};

	const handleCloseViewDialog = () => {
		viewDialogVisible.value = false;
		currentDetail.value = null;
	};

	const handleCloseApproveDialog = () => {
		approveDialogVisible.value = false;
		currentDetail.value = null;
		approveForm.applicationId = "";
		approveForm.operate = 1;
		approveForm.operateContent = "";
	};

	const handleCloseFileDialog = () => {
		fileDialogVisible.value = false;
		currentFiles.value = [];
	};
	const uploadSuccess = (fileIds) => {
		fileList.value = fileIds;
	};
	// 提交表单
	const handleSubmit = async () => {
		if (!formRef.value) return;

		try {
			await formRef.value.validate();
			submitting.value = true;

			// 处理文件ID
			const fileIds = fileList.value.map((file) => file.uid).join(",");

			const submitData = {
				...formData,
				fileIds,
			};

			if (dialogType.value === "add") {
				await addBusinessApplication(submitData);
				ElMessage.success("申请提交成功");
			} else {
				await updateBusinessApplication(submitData);
				ElMessage.success("申请更新成功");
			}

			dialogVisible.value = false;
			loadApplicationList();
		} catch (error) {
			console.error("提交失败:", error);
			if (error.errors) {
				return;
			}
			ElMessage.error("操作失败");
		} finally {
			submitting.value = false;
		}
	};

	// 提交审批
	const handleApproveSubmit = async () => {
		if (!approveFormRef.value) return;

		try {
			await approveFormRef.value.validate();
			approving.value = true;

			await handleApplication(approveForm);
			ElMessage.success("审批操作成功");
			approveDialogVisible.value = false;
			loadApplicationList();
		} catch (error) {
			console.error("审批失败:", error);
			if (error.errors) {
				return;
			}
			ElMessage.error("审批操作失败");
		} finally {
			approving.value = false;
		}
	};

	// 导出数据
	const handleExport = () => {
		ElMessage.info("导出功能开发中");
	};

	// 处理分页大小变化
	const handleSizeChange = (size) => {
		pagination.pageSize = size;
		pagination.currentPage = 1;
		loadApplicationList();
	};

	// 处理当前页变化
	const handleCurrentChange = (page) => {
		pagination.currentPage = page;
		loadApplicationList();
	};

	// 修改权限判断函数，增加空值校验
	const canApprove = (row) => {
		// 先判断 row 是否存在，避免 null/undefined 导致的报错
		if (!row) return false;
		// 只有待审批状态的申请可以审批（状态值根据实际业务调整）
		return row.applicationStatus === 1;
	};

	// 同步修复其他权限判断函数，增加空值保护
	const canEdit = (row) => {
		if (!row) return false;
		return row.applicationStatus === 1;
	};

	const canDelete = (row) => {
		if (!row) return false;
		return [1, 2, 3].includes(row.applicationStatus);
	};

	// 工具函数
	const getApplicationTypeTag = (type) => {
		const types = {
			1: "primary",
			2: "success",
			3: "warning",
			4: "info",
		};
		return types[type] || "info";
	};

	const getApplicationTypeText = (type) => {
		const typeMap = applicationTypeOptions.value.find(
			(item) => Number(item.dictValue) === type
		);
		return typeMap ? typeMap.dictLabel : type || "-";
	};

	const getApplicationStatusTag = (status) => {
		const statuses = {
			0: "info", // 草稿
			1: "warning", // 待提交
			2: "primary", // 待审批
			3: "success", // 已通过
			4: "danger", // 已驳回
		};
		return statuses[status] || "info";
	};

	const getApplicationStatusText = (status) => {
		const statusMap = applicationStatusOptions.value.find(
			(item) => Number(item.dictValue) === status
		);
		return statusMap ? statusMap.dictLabel : status || "-";
	};

	const getUserName = (userId) => {
		// 实际项目中根据用户ID获取用户名
		return `用户${userId}`;
	};

	const getFileCount = (fileIds) => {
		if (!fileIds) return 0;
		return fileIds.split(",").length;
	};

	const formatDateTime = (dateTimeString) => {
		if (!dateTimeString) return "-";
		try {
			return dayjs(dateTimeString).format("YYYY-MM-DD HH:mm:ss");
		} catch {
			return dateTimeString;
		}
	};

	const formatFileSize = (bytes) => {
		if (!bytes) return "-";
		const sizes = ["B", "KB", "MB", "GB"];
		const i = Math.floor(Math.log(bytes) / Math.log(1024));
		return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + " " + sizes[i];
	};
</script>

<style scoped lang="scss">
	.business-application-container {
		padding: 20px;
	}

	.page-header {
		margin-bottom: 20px;
		text-align: center;
	}

	.page-title {
		font-size: 24px;
		font-weight: 600;
		color: #303133;
		margin: 0 0 8px 0;
	}

	.page-subtitle {
		font-size: 14px;
		color: #909399;
		margin: 0;
	}

	.search-card {
		margin-bottom: 20px;
	}

	.search-form {
		.el-row {
			margin-bottom: 0;
		}
	}

	.form-actions {
		padding-top: 29px;
		text-align: center;
	}

	.action-card {
		margin-bottom: 20px;
	}

	.action-buttons {
		display: flex;
		gap: 10px;
		flex-wrap: wrap;
	}

	.table-card {
		margin-bottom: 20px;
	}

	.pagination-container {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	.empty-table {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	.application-form {
		.el-row {
			margin-bottom: 0;
		}
	}

	.application-detail {
		max-height: 60vh;
		overflow-y: auto;
	}

	.content-text {
		white-space: pre-wrap;
		word-break: break-word;
		line-height: 1.5;
	}

	.file-list {
		display: flex;
		align-items: center;
	}

	.file-list-dialog {
		max-height: 400px;
		overflow-y: auto;
	}

	.empty-files {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	.mt-3 {
		margin-top: 16px;
	}

	:deep(.el-table) {
		.cell {
			white-space: nowrap;
			text-align: center;
		}

		th {
			text-align: center;
		}
	}

	:deep(.el-descriptions) {
		margin-bottom: 16px;
	}

	:deep(.el-descriptions__title) {
		font-size: 16px;
		font-weight: bold;
		color: #303133;
	}

	:deep(.el-descriptions__label) {
		font-weight: 500;
		color: #606266;
	}

	:deep(.el-descriptions__content) {
		color: #303133;
	}

	:deep(.el-card) {
		margin-bottom: 20px;
	}

	:deep(.el-card):last-child {
		margin-bottom: 0;
	}

	@media (max-width: 768px) {
		.search-form .el-col {
			margin-bottom: 15px;
		}

		.action-buttons {
			flex-direction: column;
			align-items: stretch;
		}

		.application-form .el-col {
			margin-bottom: 15px;
		}
	}
</style>
